package com.itlin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itlin.bean.Employee;
import com.itlin.bean.PageParam;
import com.itlin.common.R;
import com.itlin.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

/**
 * @author 所谓伊人
 * @date 2022/3/19 - 17:07
 */
@Slf4j
@RequestMapping("/employee")
@RestController
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session) {
        // 1. 调用service
        Employee loginEmployee = employeeService.login(employee);


        //2. 响应
        if(loginEmployee  != null){ //成功

            //2.1 把查询出来的员工对象保存到session作用域
            session.setAttribute("employee" , loginEmployee);
            //2.2 给页面一个响应。
            return R.success(loginEmployee);
        }else{ //失败
            return R.error("用户名或者密码错误");
        }
    }

    @PostMapping("/logout")
    public R<Employee> logout(HttpSession session) {

        session.invalidate();

        return R.success("退出成功");
    }

    @PostMapping
    public R<Employee> add(@RequestBody Employee employee, HttpServletRequest request) {

        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

        /*employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());*/

        /*Employee employee1 = (Employee) request.getSession().getAttribute("employee");
        employee.setCreateUser(employee1.getId());
        employee.setUpdateUser(employee1.getId());*/

        int row = employeeService.add(employee);

        if (row > 0) {
            return R.success("员工添加成功");
        }

        return R.error("员工添加失败");
    }

    @GetMapping("/page")
    public R findPage(PageParam pageParam) {

        IPage<Employee> page = employeeService.findPage(pageParam);

        return R.success(page);
    }

    @PutMapping
    public R<Employee> update(@RequestBody Employee employee, HttpSession session) {

        // Employee user = (Employee) session.getAttribute("employee");

        /*employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(user.getId());*/

        int row = employeeService.update(employee);

        if (row > 0) {
            return R.success("更新成功");
        }

        return R.error("更新失败");

    }

}
